<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/15 0015
 * Time: 上午 9:58
 */

namespace App\Api\Service\Stock\Controllers;

use Framework\BaseClass\Api\Controller;
use App\Eloquent\Ygt\Stock;
use App\Eloquent\Ygt\DepartmentUser;
use App\Eloquent\Ygt\Product;
use App\Engine\Stock as StockEngine;
use App\Engine\Func;
use App\Engine\Product as EngineProduct;
use App\Eloquent\Ygt\Message;
use App\Eloquent\Ygt\StockCustomer;
use App\Eloquent\Ygt\ProductCustomer;

class CustomerController extends Controller
{
    public function stockin(){
        $user_id        = Func::getHeaderValueByName( 'userid' );
        $info           = DepartmentUser::getCurrentInfo( $user_id );

        $params = request()->only('product_id','customer_id','number');
        $rules = [
            'product_id' => 'required|numeric',
            'customer_id' => 'required|numeric',
            'number' => 'required|numeric',
        ];
        $this->validateRequestParameters($params, $rules);

        $StockCustomerData = [
            'uid' => $user_id,
            'customer_id' => $params['customer_id'],
        ];

        $StockCustomerModel = new StockCustomer();
        $stockInId = $StockCustomerModel->insertOneData($StockCustomerData,'id');


        $water_no = StockEngine::createWaterNo();
        $stockData[] = [
            'number' => $params['number'],
            'product_id' => $params['product_id'],
            'company_id' => $info->company_id,
            'operate_uid' => $user_id,
            'water_no' => $water_no,
            'relate_type' => 4,
            'relate_id' => $stockInId,
        ];
        if($stockResult = StockEngine::addStockData($stockData)){
            //客户材料库存的修改

            $customerStock = ProductCustomer::firstOrCreate(
                ['product_id' => $params['product_id'], 'customer_id' => $params['customer_id']]
            );
//            dd($customerStock);
            $customerStock->increment('number', $params['number']);
            $customerStock->save();
        }else{
            xThrow(ERR_CUSTOMER_PRODUCT_STOCK_FAIL);
        }
    }
}